package com.robusta.app.impl;

import com.robusta.app.api.SpreadsheetModelPersister;
import com.robusta.app.domain.spreadsheet.Model;
import com.robusta.app.model.spreadsheet.loader.WorkbookInfoDescribedWorkbookContentModelBuilder;
import com.robusta.app.model.spreadsheet.loader.WorkbookLoader;
import com.robusta.app.persistence.SpreadsheetModelRepository;
import com.robusta.app.persistence.WorkbookMetadataRepository;
import com.robusta.spreadsheet.describe.WorkbookInfo;
import com.robusta.spreadsheet.model.Workbook;
import com.robusta.spreadsheet.model.exception.WorkbookException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.xml.bind.JAXBException;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@Service
public class BuildSpreadsheetModelAndPersistToRepository implements SpreadsheetModelPersister {
    private WorkbookMetadataRepository workbookMetadataRepository;
    private SpreadsheetModelRepository spreadsheetModelRepository;

    @Autowired
    public BuildSpreadsheetModelAndPersistToRepository(WorkbookMetadataRepository workbookMetadataRepository, SpreadsheetModelRepository spreadsheetModelRepository) {
        this.workbookMetadataRepository = workbookMetadataRepository;
        this.spreadsheetModelRepository = spreadsheetModelRepository;
    }

    @Override
    @Transactional
    public void buildModelFromSpreadsheetAndPersist(String templateName, InputStream workbookContent) throws JAXBException, IOException, WorkbookException {
        WorkbookInfo workbookInfo = workbookMetadataRepository.findByName(templateName).templateAsWorkbookInfo();
        Workbook workbook = new WorkbookLoader(workbookInfo).load(workbookContent);
        List<Model> modelList = new WorkbookInfoDescribedWorkbookContentModelBuilder(workbookInfo, workbook).build();
        spreadsheetModelRepository.save(modelList);
    }
}
